package peer.webserver;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import peer.Config;
import peer.httpoutput.HttpProcessor;

public class AppletRequest  implements Runnable{
	Socket socket;
	Thread mainThread;
	DataInputStream dis;
	DataOutputStream dos;
	InputStream is=null;
	OutputStream os=null;
	HttpProcessor hp;
	HashMap castMemberTable;
	AppletRequest(Socket socket){
		this.socket=socket;
		mainThread=new Thread(this);
		mainThread.start();
	}
	@SuppressWarnings("deprecation")
	public void run() {
		
		try {
			is=socket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			os=socket.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		dis=new DataInputStream(is);
		dos=new DataOutputStream(os);
		String str=null;
		try {
		while(true){
			str=dis.readLine();
			if(str!=null){
				//System.out.println(str);
				if(str.startsWith("GET")){
					int index=str.indexOf('/')+1;
					int index2=str.indexOf(' ',index);
					String str2=str.substring(index,index2);
					String filePath=Config.webDir+str2;
					final File file=new File(filePath);
					System.out.println(str2+"  "+file);
					new Thread(){
						public void run(){
							if(file.exists()&file.isFile()){
								SimpleDateFormat dateFormat =new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss 'GMT'", new Locale ("En", "Us", "Unix"));
								String timeStr = dateFormat.format(new Date(file.lastModified()));
								String s2="HTTP/1.1 200 OK\r\n"+"Content-Type: application\\octet-stream"+"\r\n"+"Content-Length: "+file.length()+"\r\n"+"Server: HttpServer\r\n"+"Accept-Ranges: bytes\r\n"+"Last-Modified: "+timeStr+"\r\n"+"\r\n";
								FileInputStream fis=null;
								try {
									dos.write(s2.getBytes());
									byte[] buffer=new byte[1024*100];
									int length=0;
									fis=new FileInputStream(file);
									while(length!=-1){
										length=fis.read(buffer);
										dos.write(buffer);
									}
									dos.flush();
								} catch (IOException e) {
									return;
								}finally{
									if(fis!=null){
										try {
											fis.close();
										} catch (IOException e) {
											
										}
									}
									try {
										socket.close();
									} catch (IOException e) {
										//e.printStackTrace();
									}
								}
							}else{
								try {
									socket.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}.start();
				}
			}else{
				break;
			}
		}
		} catch (IOException e1) {
			//e1.printStackTrace();
		}
	}
}
